//that.js
import regeneratorRuntime from './utils/runtime.js';
import { shareBind,paramGet } from './utils/imapi.js';

var log = require('./utils/log.js') // 引用上面的log.js文件
let livePlayer = requirePlugin('live-player-plugin')
var that;
App({
/**
  * 当小程序初始化完成时，会触发 onLaunch（全局只触发一次）
  */
  onLaunch: function () {
    var that = this;

    this.autoUpdate(); //检测自动更新

    wx.setStorage({key:'login_time',data:Date.parse(new Date())}) // 保存授权得时间 这个游客得, 也有超时时间

    wx.getSystemInfo({
      success: e => {
        that.globalData.screenHeight = e.screenHeight;
        that.globalData.screenWidth = e.screenWidth;
        that.globalData.StatusBar = e.statusBarHeight;
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
          that.globalData.Custom = capsule;
          that.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
        } else {
          that.globalData.CustomBar = e.statusBarHeight + 50;
        }
        console.log('=====型号model:',e.model)
        const modelInclude = ["iPhone X", 'iPhone XR', "iPhone XS", "iPhone XS MAX",'IPHONE12','iPhone 7'];
        //var flag = false;//是否X以上机型
        for (let i = 0; i < modelInclude.length;i ++){
         //模糊判断是否是modelInclude 中的机型,因为真机上测试显示的model机型信息比较长无法一一精确匹配
         /* if (e.model.indexOf(modelInclude[i]) != -1){
            that.globalData.isIphonex = 1;
            break
          }*/


          // 直接处理所有iphone
          if(e.model.toLowerCase().indexOf('iphone')!=-1){
            that.globalData.isIphonex = 1;
            break
          }
        }

        console.log('====isIphonex : ',that.globalData.isIphonex)

        log.info('====isIphonex : ',that.globalData.isIphonex)

      }
    })
  },
  autoUpdate:function(){
    console.log(new Date())
    var self=this
    // 获取小程序更新机制兼容
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      //1. 检查小程序是否有新版本发布
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          //2. 小程序有新版本，则静默下载新版本，做好更新准备
          updateManager.onUpdateReady(function () {
            console.log(new Date())
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  //3. 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                } else if (res.cancel) {
                  //如果需要强制更新，则给出二次弹窗，如果不需要，则这里的代码都可以删掉了
                  wx.showModal({
                    title: '温馨提示~',
                    content: '本次版本更新涉及到新的功能添加，旧版本无法正常访问的哦~',
                    success: function (res) {     
                      self.autoUpdate()
                      return;                 
                      //第二次提示后，强制更新                      
                      if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                      } else if (res.cancel) {
                        //重新回到版本更新提示
                        self.autoUpdate()
                      }
                    }
                  })
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            })
          })
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  onShow(options) {

    let that = this;

    console.log("=====app.onShow: ",options)

   

    // 分享卡片入口场景才调用getShareParams接口获取以下参数
   // console.log('打印一下'+options);

    if (options.scene == 1007 || options.scene == 1008 || options.scene == 1044 || options.pluginScene === 1154 || options.pluginScene === 1155) {
      livePlayer.getShareParams()
        .then(res => {
          // 房间号
          console.log('get room id', res.room_id)
          // 用户openid
          console.log('get openid', res.openid)
          // 分享者openid，分享卡片进入场景才有
          console.log('get share openid', res.share_openid)
          // 开发者在跳转进入直播间页面时，页面路径上携带的自定义参数，这里传回给开发者
          console.log('get custom params', res.custom_params)

          shareBind({ room_id: res.room_id, openid: res.openid, parent_openid: res.share_openid, source_type: 'C' })

        }).catch(err => {
          console.log('get share params', err)
        })
    }

    


  },
 

   /**
  * 当小程序从前台进入后台，会触发 onHide
  */
 onHide: function() {
   console.log('==== app.onHide')
 },
  onError:function(msg){
    console.log(' === onError...')
    log.error('onError:',msg)
  },
  
  is_auth(need_login) {  //判断用户是否授权过； true:已授权  false:未授权


    try {
      let userInfo = wx.getStorageSync('userInfo')
      var timestamp = Date.parse(new Date());
      var login_time = wx.getStorageSync('login_time')  || timestamp
      if (timestamp - login_time >=  24 * 60 * 60 * 1000) { //超时 24 小时 24 * 60 * 60 * 1000
      
        wx.clearStorage();
        this.globalData.userInfo={} //这里 需要设置
        userInfo={}
        
      }
      if (userInfo == null || userInfo == '' || userInfo.uid == '0' || userInfo.uid == '' || !userInfo.uid) {
        if(need_login){
          wx.showModal({
            title: '需要登陆',
            content: '',
            cancelText:'取消',
            confirmText:'我的请先登陆哦！',
            confirmColor:'#F95A4B',
            success (res) {
              if (res.confirm) {//确认
                wx.navigateTo({
                  url: '/pages/login/login',
                })
              } else if (res.cancel) {//取消
                
              }
            }
          })
          
        }
        return false
      }
      return true
    } catch (err) {
      return false
    }


  },
  is_disable_keywords(key){ // 是否是禁止搜索词

    let disable_search_keywords= this.globalData.configs.disable_search_keywords

    if(disable_search_keywords!=null && disable_search_keywords.length>0){

      let keywords=disable_search_keywords.split(',')

      for(var i=0;i<keywords.length;i++){
        if(keywords[i]==key){
          return true
        }

      } 
      return false
    }



  },


  is_in_downloadUrls(url){ // 判断 当前下载的URL 是否已经下载组件支持
  
    let configs=this.globalData.configs
    if(configs&&configs.weapp_download_url){

      //[url1,url2]
      let urls=configs.weapp_download_url.split(';')
      // https://img.xingkonglian.net
      //https://img.xingkonglian.net/img/1.png
      // http://img.xingkonglian.net/img/1.png

      for(var i=0;i<urls.length;i++){

        let new_url=url.replace(urls[i],'')
        if(new_url!=url){
          // 有匹配
          return true
        }

      }

      return false
    }

    return false

  },

  
  sceneProcess:function(options){ //返回是否继续往下执行   0: 继续  1：停止


    if(options.scene){

      let scene=decodeURIComponent(options.scene)
      if(options && scene){

        var param =scene
        if(param && param.indexOf(',')!=-1){
  
          // 场景,用户uid
           let s_u=param.split(',')
           let scene_id=s_u[0]  //场景ID
           let share_uid=s_u[1] // share_uid


           if(scene_id==8){  // 商品详情 小程序码
             let p=s_u[2]
             let item_id=s_u[3]

             wx.navigateTo({
               url: '/pages/module/productDetail/productDetail?scene='+scene_id+'&share_uid='+share_uid+'&p='+p+'&id='+item_id,
             })
             return 

           }
        }
      }

    }


  },


  globalData: {
    is_test: true,
	// test:list,
    // cur_path: 'index', update to storage
    is_need_reload: false,
    is_over_login:false,
    visitListData: '',
    copyData: '',
    sence: '',
    is_audit: true,
    session_key: '',
    //token: '', // update to storage
    screenHeight: 0,
    screenWidth: 0,
    isIphonex: 0,
    uid: '',//最好不要使用
    cur_donate: {},
    cur_product: {},
    cur_product_buy:{}, //当前购买的商品
    cur_scm:{}, // 当前选择的社群
    share_uid:'', //保存分享者uid
    version: 'v1.0.24', // 版本： 通过版本控制审核
    userInfo: {},
    configs:{}, //项目的配置； 来自b_param 表 key:value 格式
    configs_keys:"weapp_download_url,about_me,disable_search_keywords,is_weapp_qr_fans_generator,bk_share_num,miaodong_xingpin,taobao_search_enable,over_login_options_enable,mch_mgr_login_url,anchor_earnest_money,tb_relation_enable", 
    ColorList: [{
      title: '嫣红',
      name: 'red',
      color: '#e54d42'
    },

    {
      title: '桔橙',
      name: 'orange',
      color: '#f37b1d'
    },
    {
      title: '明黄',
      name: 'yellow',
      color: '#fbbd08'
    },
    {
      title: '橄榄',
      name: 'olive',
      color: '#8dc63f'
    },
    {
      title: '森绿',
      name: 'green',
      color: '#39b54a'
    },
    {
      title: '天青',
      name: 'cyan',
      color: '#1cbbb4'
    },
    {
      title: '海蓝',
      name: 'blue',
      color: '#0081ff'
    },
    {
      title: '姹紫',
      name: 'purple',
      color: '#6739b6'
    },
    {
      title: '木槿',
      name: 'mauve',
      color: '#9c26b0'
    },
    {
      title: '桃粉',
      name: 'pink',
      color: '#e03997'
    },
    {
      title: '棕褐',
      name: 'brown',
      color: '#a5673f'
    },
    {
      title: '玄灰',
      name: 'grey',
      color: '#8799a3'
    },
    {
      title: '草灰',
      name: 'gray',
      color: '#aaaaaa'
    },
    {
      title: '墨黑',
      name: 'black',
      color: '#333333'
    },
    {
      title: '雅白',
      name: 'white',
      color: '#ffffff'
    },
    ],
    selected: 0,
    tabList: [
      [{
        index: 0,
        pagePath: "/pages/tabbar/index/index",
        iconPath: "/images/tabbar/index_default.png",
        selectedIconPath: "/images/tabbar/index_active.png",
        text: "星品",
        visible:true
      }, {
        index: 1,
        pagePath: "/pages/tabbar/live/live",
        iconPath: "/images/tabbar/live_default.png",
        selectedIconPath: "/images/tabbar/live_active.png",
        text: "星播",
        visible:false
      }, {
        index: 2,
        pagePath: "/pages/tabbar/competitive/competitive",
        iconPath: "/images/tabbar/quality_default.png",
        selectedIconPath: "/images/tabbar/quality_active.png",
        text: "星选",
        visible:true
      }, {
        index: 3,
        pagePath: "/pages/tabbar/serveDesc/serveDesc",
        iconPath: "/images/tabbar/serveDesc_default.png",
        selectedIconPath: "/images/tabbar/serveDesc_active.png",
        text: "星院",
        visible:true
      }],
      [{
        index: 4,
        pagePath: "/pages/tabbar/my/my",
        iconPath: "/images/tabbar/my_default.png",
        selectedIconPath: "/images/tabbar/my_active.png",
        text: "我的",
        visible:true
      }]
    ],
  }
})